<template>
  <view class="w100  pl-30 pr-30">
    <view class="btn" @click="handelSubmit">提交问答</view>
    <view class="pb-60">
      <view class="fs-26 mt-20 mb-20 col333" style="display: flex;color: #8a9390">
        {{ currentIndex + 1 }}.{{ currentQuestion.type == 1 ? '单选题' : currentQuestion.type == 2 ? '判断题' : '多选题' }} (
        {{ currentQuestion.type == 1 ? itemData.selectScore : currentQuestion.type == 2 ? itemData.judgeScore :
          itemData.multipleScore }} 分 )
      </view>
      <view class="rowsb rowsm mb-20" style="justify-content: flex-start;">
        <view v-html="currentQuestion.questionContent"></view>
        <text>（{{ (currentQuestion.selected || []).join('、') }}）</text>
      </view>
      <view v-for="(it, index) in currentQuestion.questionBankOptionList" :key="it.title">
        <view class="answer" style="display: flex" @click="selectAnswer(it.name)">
          <view class="unchecked" :class="{ 'active': currentQuestion.selected.includes(it.name) }"> {{ it.name }}</view>
          <view v-html="it.content"></view>
        </view>
      </view>
    </view>

    <!-- 按钮 -->
    <view class="w100 rowsb rowsm btns">
      <view class="w30 h-84 col333 pl-40" @click="preQuestion">上一题</view>
      <view class="w30 h-84 col333" @click="openModal">题卡</view>
      <view class="w30 h-84 col333 pr-40" @click="nextQuestion">下一题</view>
    </view>

    <!-- 全屏弹窗 -->
    <view v-if="isModalVisible" class="modal-overlay" @click="closeModal">
      <view class="modal-content" @click.stop>
        <!-- 弹窗内容 -->
        <view class="modal-header">
          <text>题卡</text>
        </view>
        <view class="modal-body">
          <view class="item-warp">
            <view class="item" :class="{ 'activeItem': item.selected.length > 0, 'activeCurrent': currentIndex == index }"
              v-for="(item, index) in problemList" :key="index" @click="changeBank(index)">{{ index + 1 }}</view>
            <view class="item" v-if="problemList.length % 4 == 2" style="visibility: hidden;"></view>
            <view class="item" v-if="problemList.length % 4 == 2" style="visibility: hidden;"></view>
            <view class="item" v-if="problemList.length % 4 == 3" style="visibility: hidden;"></view>
          </view>
        </view>
        <view class="modal-footer">
          <button @click="closeModal">关闭</button>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      problemList: [],
      currentIndex: 0,
      selected: '',
      itemData: {},
      isModalVisible: false, // 控制弹窗的显示与隐藏
    }
  },
  computed: {
    currentQuestion() {
      return this.problemList[this.currentIndex] || {};
    }
  },
  onLoad(e) {
    this.itemData = JSON.parse(e.item);
    uni.setNavigationBarTitle({
      title: this.itemData.name
    })
    this.getList();
  },
  onBackPress(e) {
    if (e.from === 'backbutton') {
      this.cancel();
      return true  // 阻止返回
    }
  },
  onUnload(e) {
    if (e === undefined || e.from === 'backbutton') {
      this.cancel();
      return true  // 阻止返回
    }
  },

  methods: {
    cancel() {
      uni.showModal({
        title: '温馨提示',
        content: `是否确定退出当前作答？`,
        confirmText: "继续答题",
        cancelText: "确定",
        success: (res) => {
          if (res.cancel) {
            uni.navigateBack({ delta: 1 })
          } if (res.confirm) {
            return false
          }

        }
      });
    },
    getList() {
      this.$tools.axiosFromToken('post', `student/test/paper/user/getTestPaperInfo`, { id: this.itemData.id }, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg);
        res.data.forEach(item => {
          this.problemList.push({ ...item, selected: [] });
        })
      })
    },
    //  toPage() {
    // this.problemList.forEach()
    //    uni.navigateTo({
    //      url: '/pagesCopy/trivia/questionCard'
    //    })
    //  },
    // 打开弹窗
    openModal() {
      this.isModalVisible = true;
    },
    // 关闭弹窗
    closeModal() {
      this.isModalVisible = false;
    },
    changeBank(index) {
      this.currentIndex = index;
      this.isModalVisible = false;
    },
    selectAnswer(optionName) {
      this.currentQuestion.questionBankOptionList.forEach(v => v.selected = null);

      if (this.currentQuestion.type == 1 || this.currentQuestion.type == 2) {
        this.currentQuestion.selected = [optionName];  // 清空并设置选中的选项
        const selectIndex = this.currentQuestion.questionBankOptionList.findIndex(y => y.name == optionName);
        this.currentQuestion.questionBankOptionList[selectIndex].selected = 1;
      } else if (this.currentQuestion.type === 3) {
        const selected = this.currentQuestion.selected;
        let index = selected.indexOf(optionName);
        if (index === -1) {
          // 如果没有选中，添加到选中的数组中
          selected.push(optionName);
        } else {
          // 如果已选中，取消选择
          selected.splice(index, 1);
        };
        this.currentQuestion.selected.forEach(v => {
          const selectIndex = this.currentQuestion.questionBankOptionList.findIndex(y => y.name == v);
          this.currentQuestion.questionBankOptionList[selectIndex].selected = 1;
        })
      }
    },
    // 上一题
    preQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },
    // 下一题
    nextQuestion() {
      if (this.currentIndex < this.problemList.length - 1) {
        this.currentIndex++;
      }
      if (this.currentIndex == this.problemList.length - 1) {
        this.$tools.showtt('此题为最后一题')
      }
    },
    handelSubmit() {
      let unanswerNum = 0;
      this.problemList.forEach(v => {
        if (v.selected.length === 0) {
          unanswerNum++;
        }
      })
      if (unanswerNum > 0) {
        uni.showModal({
          title: '温馨提示',
          content: `您还有${unanswerNum}题未做，是否继续答题？`,
          confirmText: "提前交卷",
          cancelText: "继续答题",
          success: (res) => {
            if (res.confirm) {
              this.SubmitPaper()
            }
          },
          fail: (err) => {
            console.log('取消')
          }
        });
      } else {
        this.SubmitPaper()
      }
    },
    SubmitPaper() {
      const data = {
        selectScore: this.itemData.selectScore,
        judgeScore: this.itemData.judgeScore,
        multipleScore: this.itemData.multipleScore,
        score: this.itemData.score,
        testPaperId: this.itemData.id,
        questionBankList: this.problemList
      }
      this.$tools.axiosFromToken('post', `test/paper/user/commit`, data, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg);
        setTimeout(() => {
          this.$tools.showtt('交卷成功')
        }, 500)
        this.$tools.goBack(2)
      })
    }
  },
}
</script>
<style lang="scss">
page {
  background-color: #fff;
}

.btn {
  text-align: right;
  color: #17b51a;
  font-size: 30rpx;
}

.answer {
  padding: 24rpx;
  background: #f4f8fb;
  margin-bottom: 40rpx;
  font-size: 26rpx;
  color: #333;
  border-radius: 20rpx;
}

.unchecked {
  width: 40rpx;
  height: 40rpx;
  border-radius: 20rpx;
  text-align: center;
  margin-right: 10rpx;
  border: 2rpx solid #ced1d5;
  color: #bebebe;
}

.active {
  background: #08c67f;
  border: 0;
  color: #fff;
}

.btns {
  width: 100%;
  height: 50px;
  line-height: 50px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
}

.item-warp {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  // align-content: flex-start;

  .item {
    // width: 45px;
    // height: 45px;
    width: 16%;
    aspect-ratio: 1 / 1;
    margin: 10px;
    border-radius: 50%;
    border: 1px solid #ededed;
    text-align: center;
    line-height: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #bac4c3;
  }

  .activeItem {
    background: #ecfff9;
    border: 0;
    color: #0ac17c;
  }

  .activeCurrent {
    background: #f6f6f6;
  }
}

/* 弹窗的遮罩层样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
}

/* 弹窗内容样式 */
.modal-content {
  background-color: white;
  width: 80%;
  height: 80%;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

/* 弹窗的头部 */
.modal-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 弹窗的主体部分 */
.modal-body {
  flex: 1;
  font-size: 16px;
  margin-bottom: 20px;
}

/* 弹窗的底部 */
.modal-footer {
  height: 30px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 按钮样式 */
button {
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;

}

::v-deep uni-button {
  font-size: 14px;
}
</style>
 